﻿using System;
using System.Reflection;

namespace Expect.Report.Word
{
    using System.Collections.Generic;
    using System.Linq;

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;

    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0 || (args.Length == 1 && args[0].ToLower() == "-help"))
            {
                HelpGenerator.Generate();
                return;
            }

            
            try
            {
                WriteHeader();
                if (args[0].ToLower() == "-liststyles")
                {
                    ListStyles(args);
                    return;
                }

                GenerateReport(args);
            }
            catch (ReflectionTypeLoadException rtle)
            {
                foreach (var loaderException in rtle.LoaderExceptions)
                {
                    Console.WriteLine(loaderException.ToString());                    
                }
                System.Environment.ExitCode = 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                System.Environment.ExitCode = 1;
                //Console.ReadKey();
            }
        }

        private static void ListStyles(string[] args)
        {
            ReportConfiguration cfg = ReportConfiguration.ReadFrom(args);

            if (!cfg.ValidateForStyleList()) return;

            var styles = new ReportGenerator(cfg).ReadTemplateStyles();
            Console.WriteLine("#### paragraphs styles (id#name) ####");
            ShowStyles(styles.Where(s => s.StyleType == StyleValues.Paragraph));
            Console.WriteLine(string.Empty);
            Console.WriteLine(string.Empty);

            Console.WriteLine("#### tables styles (id#name) ####");
            ShowStyles(styles.Where(s => s.StyleType == StyleValues.Table));
            
        }

        private static void ShowStyles(IEnumerable<WordStyleRef> parStyles)
        {
            foreach (var style in parStyles)
            {
                Console.WriteLine(style.Id + " # " + style.Name);
            }
        }

        static void WriteHeader()
        {
            Console.WriteLine(string.Empty); 
            Console.WriteLine("Expect Word report generation v" + typeof(ReportGenerator).Assembly.GetName().Version);
            Console.WriteLine(string.Empty);
        }

        static void GenerateReport(string[] args)
        {
            ReportConfiguration cfg = ReportConfiguration.ReadFrom(args);

            if (cfg.Validate())
            {
                new ReportGenerator(cfg).Execute();
                Console.WriteLine("Generation succesfull");
            }
        }
    }
}
